# auth/jwt_manager.py

import jwt
import datetime
import os

# 使用环境变量，生产环境务必设置 JWT_SECRET
SECRET = os.getenv("JWT_SECRET", "dev-secret-change-in-production")

def create_token(user_id: str, role: str = "user") -> str:
    """
    生成 JWT 令牌
    :param user_id: 用户标识（如 'admin'）
    :param role: 用户角色
    :return: JWT token 字符串
    """
    payload = {
        "sub": user_id,
        "role": role,
        "exp": datetime.datetime.utcnow() + datetime.timedelta(hours=2),
        "iat": datetime.datetime.utcnow()
    }
    return jwt.encode(payload, SECRET, algorithm="HS256")

def decode_token(token: str):
    """
    解码 JWT 令牌
    :param token: JWT 字符串
    :return: payload dict 或 None（如果无效或过期）
    """
    try:
        return jwt.decode(token, SECRET, algorithms=["HS256"])
    except jwt.ExpiredSignatureError:
        return None
    except jwt.InvalidTokenError:
        return None

def require_auth(f):
    """
    Flask 装饰器：保护路由
    """
    from functools import wraps
    from flask import request, jsonify

    @wraps(f)
    def decorated(*args, **kwargs):
        auth_header = request.headers.get("Authorization")
        if not auth_header or not auth_header.startswith("Bearer "):
            return jsonify({"error": "缺少 Authorization 头或格式错误"}), 401
        token = auth_header.split(" ")[1]
        payload = decode_token(token)
        if not payload:
            return jsonify({"error": "无效或过期的令牌"}), 401
        request.user = payload  # 可在视图中使用
        return f(*args, **kwargs)
    return decorated